package com.lgj.auth.code.token;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.TokenRequest;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenStore;

/**
 * @author: guangjie.liao
 * @Date: 2022/11/17 11:11
 * @Description: 自定义token生成
 */
public class OauthServerTokenServices implements AuthorizationServerTokenServices {

    private DefaultTokenServices defaultTokenServices = new DefaultTokenServices();


    public OauthServerTokenServices(TokenStore tokenStore,ClientDetailsService clientDetailsService,
                                    TokenEnhancer accessTokenEnhancer,AuthenticationManager authenticationManager){
        this.defaultTokenServices.setTokenStore(tokenStore);
        this.defaultTokenServices.setClientDetailsService(clientDetailsService);
        this.defaultTokenServices.setTokenEnhancer(accessTokenEnhancer);
        this.defaultTokenServices.setAuthenticationManager(authenticationManager);

        this.defaultTokenServices.setSupportRefreshToken(true);
        this.defaultTokenServices.setAccessTokenValiditySeconds(60);
        this.defaultTokenServices.setRefreshTokenValiditySeconds(60);
    }



    @Override
    public OAuth2AccessToken createAccessToken(OAuth2Authentication authentication) throws AuthenticationException {
        return defaultTokenServices.createAccessToken(authentication);
    }

    @Override
    public OAuth2AccessToken refreshAccessToken(String refreshToken, TokenRequest tokenRequest) throws AuthenticationException {
        return defaultTokenServices.refreshAccessToken(refreshToken,tokenRequest);
    }

    @Override
    public OAuth2AccessToken getAccessToken(OAuth2Authentication authentication) {
        return defaultTokenServices.getAccessToken(authentication);
    }

    public DefaultTokenServices getDefaultTokenServices(){
        return this.defaultTokenServices;
    }
}
